package com.minelx.woods.server.entity;

import com.alibaba.fastjson.JSONObject;
import com.minelx.woods.server.entity.values.TaskValues;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.bson.types.ObjectId;

import java.util.Optional;

import static com.minelx.woods.server.entity.TaskConstants.INIT;
import static com.minelx.woods.server.entity.TaskConstants.READY;

public class Tasks {

	private final MongoCollection<Document> tasksCollection;

	public Tasks(MongoCollection<Document> tasksCollection) {
		this.tasksCollection = tasksCollection;
	}

	public TaskValues push(JSONObject taskInfo) {
		Document inserted = new Document();
		inserted.append("_id", new ObjectId());
		inserted.append("condition", INIT);
		inserted.append("info", Document.parse(taskInfo.toJSONString()));
		tasksCollection.insertOne(inserted);
		return TaskValues.from(inserted);
	}

	public void removeAll() {
		tasksCollection.deleteMany(new Document());
	}

	public Optional<Task> anyReadyTask() {
		return Optional.ofNullable(tasksCollection.find(new Document("condition", READY))
				.map(document -> id(document.get("_id").toString()))
				.first());
	}

	public Task id(String taskId) {
		return new Task(tasksCollection, taskId);
	}
}
